<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="flex justify-between">
        <el-button size="default" type="primary" @click="handleAdd">添加</el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        class="mt-3"
        stripe
        style="width: 100%"
        tooltip-effect="dark"
      >
        <el-table-column :index="indexMethod" label="序号" prop="user_code" type="index" width="100px"></el-table-column>
        <el-table-column label="名称" prop="title"></el-table-column>
        <el-table-column label="语音文件" prop="content">
          <template slot-scope="{row}">
            <audio v-if="row.content" :src="row.content" controls></audio>
          </template>
        </el-table-column>
        <el-table-column label="作品封面" prop="picture" width="200px">
          <template slot-scope="{row}">
            <el-image :lazy="true" :src="row.picture" fit="fill"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="总时长" prop="second">
          <template slot-scope="{row}">
            {{ Number(row.second) ? row.second : '' }}
          </template>
        </el-table-column>
        <el-table-column label="播放次数" prop="play_count">
          <template slot-scope="{row}">
            {{ row.play_count ? row.play_count : '' }}
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
        <el-table-column label="上架状态" prop="status">
          <template slot-scope="scoped">
            <el-tag v-if="scoped.row.status === 0" type="danger">下架</el-tag>
            <el-tag v-if="scoped.row.status === 1" type="success">上架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at"></el-table-column>

        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- <el-button
                size="mini"
                type="text"
                @click="handleCheck(scope.row)"
            >查看
            </el-button> -->
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              size="mini"
              type="text"
              @click="handleStatus(scope.row,1)"
            >上架
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="mini"
              type="text"
              @click="handleStatus(scope.row,2)"
            >下架
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDel(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <cus-pagination
        v-show="total > 0"
        :limit.sync="listQuery.perPage"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getTableData"
      />
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeDialog('form')"
    >

      <el-form ref="form" :inline="false" :model="formData" :rules="rules" label-width="170px" size="normal">
        <el-form-item label="名称" prop="title">
          <el-input
            v-model="formData.title"
            maxlength="50"
            placeholder="请输入名称"
            rows="2"
            show-word-limit
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="上传内容" prop="content">
          <div class="awardBox">
            <div :class="{'hide_box': formData.content, 'show_box': !formData.content}" class="awardInfo">
              <!-- <audio v-if="formData.content" :src="formData.content" class="avatar"></audio> -->
              <el-upload
                ref="upload"
                :auto-upload="true"
                :before-remove="beforeRemove"
                :file-list="fileList"
                :http-request="customizeUpload"
                :limit="1"
                :on-success="handlePictureSuccess1"
                action=""
                class="upload-demo"
              >
                <el-button v-if="!formData.content" size="small" type="primary">点击上传</el-button>
              </el-upload>
              <!-- <span class="closeIcon" @click="handlePictureRemove1"><i class="el-icon-delete"></i></span> -->
            </div>
          </div>
        </el-form-item>

        <el-form-item label="封面" prop="picture">
          <div class="awardBox">
            <div :class="{'hide_box': formData.picture, 'show_box': !formData.picture}" class="awardInfo"
                 style="width: 200px;"
            >
              <img v-if="formData.picture" :src="formData.picture" class="avatar"/>
              <el-upload
                v-else
                ref="upload"
                :auto-upload="true"
                :http-request="customizeUpload"
                :limit="1"
                :on-success="handlePictureSuccess2"
                action=""
                class="upload-demo"
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <span class="closeIcon" @click="handlePictureRemove2"><i class="el-icon-delete"></i></span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="总时长" prop="second">
          <el-input
            v-model="formData.second"
            placeholder="请输入总时长"
          />
        </el-form-item>
        <el-form-item label="播放次数" prop="play_count">
          <el-input
            v-model="formData.play_count"
            placeholder="请输入播放次数"
          />
        </el-form-item>

        <el-form-item label="作品排序" prop="sort">
          <el-input
            v-model="formData.sort"
            placeholder="请输入排序"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSubmit">确定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import { whiteNoiseDelete, whiteNoiseList, whiteNoiseOff, whiteNoiseSave } from '@/api/worksManagement'

export default {
  name: 'whiteNoise',
  data() {
    return {
      dialogVisible: false,
      loading: false,
      tableData: [],
      listQuery: {
        page: 1,
        perPage: 10,
        theme_id: undefined
      },
      total: 1,
      dialogTitle: '添加作品',
      formData: {
        id: undefined,
        title: undefined,
        picture: undefined,
        content: undefined,
        second: undefined,
        play_count: undefined,
        sort: undefined,
        status: undefined,
      },
      rules: {
        title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        picture: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        content: [{ required: true, message: '请上传作品', trigger: 'blur' }],
      },
      fileList: []
    }
  },
  created() {
    this.listQuery.theme_id = this.$route.query.id
    this.getTableData()
  },
  methods: {
    indexMethod(index) {
      return this.total - (this.listQuery.page - 1) * this.listQuery.perPage - index
    },
    // 网络请求
    /**
     * getTableData
     * @desc 获取表格数据
     */
    async getTableData() {
      this.loading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key] == 0 ? 0 : this.listQuery[key]
      }
      const { data, code } = await whiteNoiseList(this.listQuery)
      if (code === 200) {
        this.tableData = data.data
        this.total = data.total
      }
      this.loading = false

    },
    closeDialog(form) {
      if (this.$refs[form]) {
        this.$refs[form].clearValidate() // 清除整个表单的校验
        this.$refs[form].resetFields() // 清除整个表单的校验
      }
      this.formData = {
        id: undefined,
        title: undefined,
        picture: undefined,
        content: undefined,
        second: undefined,
        play_count: undefined,
        sort: undefined,
        status: undefined,
      }
      this.fileList = []
    },
    handleCheck() {
      this.$router.push({
        path: 'worksList',
        query: {
          id: ''
        }
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑作品'
      this.dialogVisible = true
      this.formData = JSON.parse(JSON.stringify(row))
      this.fileList = [
        {
          url: this.formData.content,
          name: this.formData.title
        }
      ]
    },
    handleStatus(row, type) {
      if (type == 1) {
        this.$confirm('确定上架该作品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          whiteNoiseOff({
            id: row.id,
            status: 1
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            }
            this.dialogVisible = false
            this.getTableData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
      if (type == 2) {
        this.$confirm('确定下架该作品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          whiteNoiseOff({
            id: row.id,
            status: 0
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            }
            this.dialogVisible = false
            this.getTableData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }

    },
    handleAdd() {
      this.dialogTitle = '创建作品集'
      this.dialogVisible = true
    },
    handlePictureSuccess1(response, file, fileList) {
      console.log(response, file, fileList)
      this.formData.content = this.ossLastImgUrl
      this.fileList = [
        {
          url: this.ossLastImgUrl,
          name: file.name
        }
      ]
      var content = file.raw
      var that = this
      var url = URL.createObjectURL(content);//获取录音时长
      var audioElement = new Audio(url);//audio也可获取视频的时长
      var duration;
      audioElement.addEventListener("loadedmetadata", function(_event) {
        duration = Math.ceil(audioElement.duration);
        console.log(duration);
        that.$set(that.formData, 'second', duration)
        console.log(that.formData.second, duration)
      });
    },
    beforeRemove(file, fileList) {
      this.fileList = []
      this.formData.content = undefined
    },
    handlePictureRemove1() {
      this.fileList = []
      this.formData.content = undefined
    },
    handlePictureSuccess2() {
      this.formData.picture = this.ossLastImgUrl
    },
    handlePictureRemove2() {
      this.formData.picture = undefined
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // for (let key in this.formData) {
          //     this.formData[key] = this.formData[key] == '' ? undefined : this.formData[key] == 0 ? 0 : this.formData[key]
          // }
          this.formData.theme_id = this.$route.query.id
          whiteNoiseSave(this.formData).then(res => {
            if (res.code === 200) {
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            }
            this.dialogVisible = false
            this.getTableData()
          })
        }
      })
    },
    handleDel(row) {
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        whiteNoiseDelete({
          id: row.id,
        }).then(res => {
          if (res.code === 200) {
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .hide_box {
    .el-upload--picture-card {
      display : none;
    }
  }

  .el-upload-list__item {
    margin-right : 1em !important;
    max-width    : 200px;
  }

}

.radioStyle {
  width         : 100px;
  margin-bottom : 15px;
}

.awardBox {
  display         : flex;
  align-items     : center;
  justify-content : flex-start;
  width           : 100%;

  .awardInfo {
    margin-right    : 10px;
    border-radius   : 4px;
    position        : relative;
    overflow        : hidden;

    display         : flex;
    align-items     : center;
    justify-content : center;

    .closeIcon {
      position        : absolute;
      top             : 0;
      bottom          : 0;
      right           : 0;
      left            : 0;
      display         : flex;
      justify-content : center;
      align-items     : center;
      font-size       : 10px;
      background      : rgba(0, 0, 0, .6);
      color           : #ffffff;
      overflow        : hidden;
      cursor          : pointer;
      font-size       : 18px;
      opacity         : 0;
      z-index         : 0;
    }
  }

  .hide_box:hover {
    .closeIcon {
      opacity : 1;
      z-index : 1;
    }
  }

  .show_box {
    .closeIcon {
      opacity : 0;
      z-index : -1;
    }
  }
}

.item {
  width : 100px;
}

.formItemBox {
  display     : flex;
  align-items : center;
  flex-wrap   : wrap;

  width       : 100%;
  overflow    : hidden;
}

::v-deep {
  .formItemBox {
    .el-form-item {
      width : 50% !important;
    }
  }

}

</style>
